import React from "react";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import { ChunkExtractor} from "@loadable/server";
// import { Helmet } from "react-helmet";
import * as middleware from '../server/middleware';
import App from "./App";
import { Request, Response } from "express";
const path = require('path');
type ServerRenderProps = {
  options: {
    manifest: object | undefined,
    template: string
  },
  req: Request,
  res:Response,
}
export async function serverRender(props: ServerRenderProps){
  const {options,req,res} = props;
	const {href, meoData, realHost, isLangDomainSite} = req;
	const {routePath: pathname, deployPath, lang, matchedRoute} = meoData;
	let Component
	const {manifest,template} = options;
	if(matchedRoute){
		Component = (await matchedRoute?.route.fetchComponent).default;
	}
	Component.initState = {
		test: '333'
	}
	console.log('matchRoutesres-------',Component);
	console.log('Component',Component);
  let serverRenderFailure = null;
	const extractor = new ChunkExtractor({ stats: manifest, entrypoints: ["app"] });
	const component = extractor.collectChunks(
		<StaticRouter location={req.url}>
			<App/>
		</StaticRouter>
	);
	// 渲染页面
	let root = "";
	try {
		root = ReactDOMServer.renderToString(component);
	} catch (e) {
		serverRenderFailure = "渲染异常";
	}
  console.log(root,'root----------------------------------');
	// const head = Helmet.renderStatic();
	// const headMetas = head.meta.toString();
	// const headLinks = head.link.toString();
	// const headScripts = head.script.toString();
	// const headStyles = head.style.toString();
	const linkTags = extractor.getLinkTags().replace(/\r?\n/g, "");
	const styleTags = extractor.getStyleTags().replace(/\r?\n/g, "");
	const scriptTags = extractor.getScriptTags().replace(/\r?\n/g, "");
	// 替换注释节点为渲染后的html字符串
	const html = `<!DOCTYPE html>
	<html lang="en">
		<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<meta name="theme-color" content="#000000" />
		<meta name="description" content="Web site created using create-react-app" />
		<title>React App</title>
		${linkTags}
		${styleTags}
		${scriptTags}
		</head>
		<body>
			<div id="root">${root}</div>
		</body>
	</html>
	`;
  res.status(200).set({ 'Content-Type': 'text/html', "Cache-Control": "max-age=60" }).end(html)
}
export {middleware};

